package software;

import java.io.*;
import java.util.ArrayList;

public class Practice {
	//读练习文件
	public ArrayList<Integer> readCSVPractice (File aFile){
		ArrayList<Integer> res = new ArrayList<Integer>();
		String filename = null;
		filename = aFile.getPath();
		BufferedReader breader = null;
		String strnum="-?[0-9]{1,3}";
		
        try{
            breader = new BufferedReader(new FileReader(filename));
            String line = null;
            while(null!=(line=breader.readLine())){
                String[] lines = line.split(",");
                for(int i=0;i<lines.length;++i) {
                	String temp=lines[i].trim();//去掉首位空格
                	if(temp.matches(strnum)) {
                		res.add(new Integer(temp));
                	}else {
                		System.out.println("字符串："+lines[i]+"不是999以内整数");
                		res.add(new Integer(-1000));//给一个错误值
                	}
                }
            }
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally{
            if(breader != null){
                try{
                    breader.close();
                }
                catch(IOException e){
                    System.out.println("Error");
                }
            }
        }
		return res;
	}
	//写练习文件
	public void WriteCSVPractice(ArrayList<String> res,File file) {
		try {
			if(!file.exists()) {
				file.createNewFile();
			}
			FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fileWriter);
			
			for(int i=0;i<res.size();++i) {
				bw.write(res.get(i)+",");
				if((i+1)%5==0)bw.write("\n");
			}
			System.out.println(file.getName()+"成功写入"+res.size()+"个结果");
			bw.close();
			fileWriter.close();
		}catch(IOException e){
            e.printStackTrace();
        }
	}
}
